"use strict";

const Service = require("egg").Service;

class HomeService extends Service {
  async user() {
    const { app } = this;
    const QUERY_STR = "name,age,height";
    const sql = `select ${QUERY_STR} from user`; // 获取 id 的 sql 语句
    try {
      const result = await app.mysql.query(sql); // mysql 实例已经挂载到 app 对象下，可以通过 app.mysql 获取到。
      return result;
    } catch (error) {
      console.log(error);
      return null;
    }
  }
  // 新增
  async addUser(name, age, height) {
    const { ctx, app } = this;
    try {
      const result = await app.mysql.insert("user", { name, age, height }); // 给 list 表，新增一条数据
      return result;
    } catch (error) {
      console.log(error);
      return null;
    }
  }
  // 编辑
  async editUser(name, age, height) {
    const { ctx, app } = this;
    try {
      const result = await app.mysql.update(
        "user",
        { name, age, height },
        {
          where: {
            name, // 从数据库中查找传入进来的名字，再修改
          },
        }
      );
      return result;
    } catch (error) {
      console.log(error);
      return null;
    }
  }

  // 删除
  async deleteUser(name) {
    const { ctx, app } = this;
    try {
      const result = await app.mysql.delete(
        'user',
        { name }
      );
      return result;
    } catch (error) {
      console.log(error);
      return null;
    }
  }
}
module.exports = HomeService;
